import { TreeSelect, message } from 'antd';
import { OriganizationUnit, IEnterpriseStruct } from 'spd-request/organization-unit';
import { createTreeFactory, INodeStruct } from 'spd-components/tree';
import { useEffect, useState, ReactElement } from 'react';
const createTree = createTreeFactory<IEnterpriseStruct>('parentId', 'id', 'parentId',  (data) => data.displayName );
const { TreeNode } = TreeSelect;
function createSelectTreeNode(tree:INodeStruct<IEnterpriseStruct>[]) {
    let result: ReactElement[] = [];
    for(let item of tree) {
        result.push(
            <TreeNode value={item.data.id} title={item.data.displayName}>
                {createSelectTreeNode(item.children)}
            </TreeNode>
        )
    }
    return result;
}
export function DepartmentSelectTree(props: {placeholder: string} = {placeholder: '请选择'}) {
    let [tree, setTree] = useState<ReactElement[]>([]);
    useEffect(() => {
        OriganizationUnit.getEnterpriseOrganizationUnits().then(({error, data}) => {
            if(error) {
                return message.error(error);
            }
            let treeData: INodeStruct<IEnterpriseStruct>[] = createTree(null, data.items);
            setTree(createSelectTreeNode(treeData));
        });
    },[]);
    return (
        <TreeSelect
            showSearch
            style={{ width: '100%' }}
            // value={value}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            placeholder={props.placeholder}
            allowClear
            treeDefaultExpandAll
            // onChange={onChange}
        >
            {tree}
        </TreeSelect>
    );
}